package dodoCal;

import java.awt.Component;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;

public class calConfig implements Serializable {
	static String appdata;
	static String fileName;
	static File configFile;

	int level;
	float price1;
	float price2;

	calConfig() {
		level = 9999;// 第一阶段张数
		price1 = 0.2f;// 第一阶段单价
		price2 = 0.12f;// 第二阶段单价
		appdata=getEnv().get("APPDATA").toString();
		if("".equals(appdata))
		{
			appdata=".";
		}
		fileName = appdata+ "\\calcfg.ini";
		//System.out.println(appdata);
		configFile = new File(fileName);
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public float getPrice1() {
		return price1;
	}

	public void setPrice1(float price1) {
		this.price1 = price1;
	}

	public float getPrice2() {
		return price2;
	}

	public void setPrice2(float price2) {
		this.price2 = price2;
	}

	public static calConfig getConfig() {
		calConfig cfg = new calConfig();// 配置
		ObjectInputStream ins = null;
		if (configFile.exists()) {
			try {
				ins = new ObjectInputStream(new FileInputStream(fileName));
				cfg = (calConfig) ins.readObject();
			} catch (Exception e) {
				alert(null, "读取配置失败！");
			}
		}
		return cfg;
	}

	public static calConfig getConfigSilencely() {
		calConfig cfg = new calConfig();// 配置
		ObjectInputStream ins = null;
		if (configFile.exists()) {
			try {
				ins = new ObjectInputStream(new FileInputStream(fileName));
				cfg = (calConfig) ins.readObject();
			} catch (Exception e) {
			}
		}
		return cfg;
	}

	public static void saveConfig(calConfig cfg) {
		try {
			ObjectOutputStream outs = new ObjectOutputStream(
					new FileOutputStream(fileName));
			outs.writeObject(cfg);
		} catch (Exception e) {
			alert(null, "保存配置失败！");
		}
	}

	public static void alert(Component c, String msg) {
		Toolkit.getDefaultToolkit().beep();
		JOptionPane.showMessageDialog(c, msg);
	}
	//获取环境变量
	public static Map getEnv() {
		Map map = new HashMap();
		String OS = System.getProperty("os.name").toLowerCase();

		Process p = null;

		/**
		 * 以windows为例.
		 */
		if (OS.indexOf("windows") > -1) {
			try {
				p = Runtime.getRuntime().exec("cmd /c set");
				BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

				String line="";

				while ((line = br.readLine()) != null) {
					String[] str = line.split("=");
					map.put(str[0], str[1]);
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		return map;
	}
}
